package com.kbs.im.client.handler;

import com.kbs.im.client.config.ClientConfig;
import com.kbs.im.client.service.ClientService;
import com.kbs.im.common.protocol.packet.request.DeviceRegisterRequestPacket;
import com.kbs.im.common.protocol.packet.request.HeartbeatRequestPacket;
import com.kbs.im.common.protocol.packet.response.HeartbeatResponsePacket;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * 心跳检测
 *
 * @author zhangzhang
 */
public class HeartBeatTimerHandler extends SimpleChannelInboundHandler<HeartbeatResponsePacket> {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        deviceRegister(ctx);
        ClientService.INSTANCE.listAllDevice(ctx.channel());
        scheduleSendHeartBeat(ctx);
        super.channelActive(ctx);
    }

    /**
     * 设备注册
     * @param ctx
     */
    private void deviceRegister(ChannelHandlerContext ctx) {
        ClientConfig.INSTANCE.setDeviceCPU("cpu_123456");
        DeviceRegisterRequestPacket requestPacket = new DeviceRegisterRequestPacket();
        requestPacket.setDeviceCPU(ClientConfig.INSTANCE.getDeviceCPU());
        ctx.channel().writeAndFlush(requestPacket);
    }

    /**
     * 心跳检测定时任务
     * @param ctx
     */
    private void scheduleSendHeartBeat(ChannelHandlerContext ctx) {
        ctx.executor().schedule(() -> {
            if (ctx.channel().isActive()) {
                System.out.println(LocalDateTime.now() + "：ping");
                ctx.channel().writeAndFlush(new HeartbeatRequestPacket());
                scheduleSendHeartBeat(ctx);
            }
        }, 10, TimeUnit.SECONDS);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HeartbeatResponsePacket msg) throws Exception {
        System.out.println(LocalDateTime.now() + ":pong......");
    }
}
